#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：file_util.py
@Author  ：平
@Date    ：2025/9/28 16:27 
"""
from pathlib import Path
import requests
from app.config.config import settings


def get_relative_file_path(file_path: str | Path):
    """
    获取文件相对路径
    Args:
        file_path: 文件路径

    Returns: 相对路径

    """
    # 确保 file_path 是相对路径
    file_path_obj = Path(file_path)
    if file_path_obj.is_absolute():
        # 如果是绝对路径，去除根部分，只保留相对路径
        file_path_obj = file_path_obj.relative_to(file_path_obj.anchor)
    return Path(settings.CACHE_DIR_PATH) / file_path_obj

def save(content: bytes, file_path: str | Path) -> Path:
    """
    保存文件到缓存文件夹中
    Args:
        content: 文件内容
        file_path: 文件路径
    """
    file = get_relative_file_path(file_path)
    file.parent.mkdir(parents=True, exist_ok=True)
    file.write_bytes(content)
    return file


def download(url: str, file_path: str):
    """
    流式下载大文件
    Args:
        url: 请求路径
        file_path: 文件路径
    """
    file = get_relative_file_path(file_path)
    file.parent.mkdir(parents=True, exist_ok=True)
    with requests.get(url, stream=True) as response:
        response.raise_for_status()
        with file.open('wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)

def delete(file_path: str):
    """
    删除文件
    Args:
        file_path: 文件路径
    """
    file = get_relative_file_path(file_path)
    if file.exists():
        file.unlink()